package com.codemes.happylist.modules;

import com.codemes.happylist.config.MenuConfig;
import com.codemes.happylist.config.MenuItem;
import com.codemes.happylist.modules.iciba.IcibaDailyPhaseView;
import com.codemes.happylist.utils.SpringContextutil;
import de.felixroske.jfxsupport.AbstractFxmlView;
import de.felixroske.jfxsupport.FXMLController;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.event.EventType;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.geometry.Rectangle2D;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Pane;
import javafx.stage.Screen;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.awt.*;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;

/**
 * @author nscoffee
 */
@Slf4j
@FXMLController
public class CodemesToolMainController implements Initializable {

    @FXML
    public Tab tabIndex;
    @FXML
    public TabPane tabContainer;
    @FXML
    public Pane pnContainer;
    @FXML
    public AnchorPane pnTitle;
    @FXML
    public AnchorPane apnLeft;
    @FXML
    public AnchorPane apnRight;
    @FXML
    public SplitPane spnMain;
    @FXML
    public TreeView<MenuItem> tvLeft;

    @Autowired
    IcibaDailyPhaseView icibaDailyPhaseView;

    @Autowired
    MenuConfig menuConfig;

    private static final Double MAIN_CONTAINER_SCALE = 0.8d;
    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {

        Rectangle2D rectangle2D = Screen.getPrimary().getBounds();
        pnContainer.setPrefHeight(rectangle2D.getHeight()*MAIN_CONTAINER_SCALE);
        pnContainer.setPrefWidth(rectangle2D.getWidth()*MAIN_CONTAINER_SCALE);

        initLayoutBind();

        initMenuList();

        tabIndex.setContent(icibaDailyPhaseView.getView());
        tabIndex.setId("0");
        tabIndex.setClosable(false);
        ImageView iconImage = new ImageView("/images/menu/home.png");
        iconImage.setFitHeight(20);
        iconImage.setPreserveRatio(true);
        tabIndex.setGraphic(iconImage);

    }

    private void initMenuList(){
        log.info("menuconfig ->{}",menuConfig);
        String rootName = menuConfig.getRoot();
        String rootIcon = menuConfig.getRootIcon();
        MenuItem rootMenu = new MenuItem();
        rootMenu.setName(rootName);
        rootMenu.setIcon(rootIcon);
        rootMenu.setId(0);
        TreeItem<MenuItem> root = createTreeItem(rootMenu);
        List<MenuItem> menuList = menuConfig.getMenuList();
        menuList.forEach(item->{
            TreeItem<MenuItem> treeItem = createTreeItem(item);
            root.getChildren().add(treeItem);
        });
        tvLeft.setRoot(root);
        tvLeft.setEditable(false);
        tvLeft.getSelectionModel().selectedItemProperty().addListener((v,old,newValue) -> {
            MenuItem menuItem = newValue.getValue();
            Integer id = menuItem.getId();
            tabContainer.getTabs().stream().filter(tab -> {
                // 找到id相同的tab
                return tab.getId().equals(String.valueOf(id));
            }).findFirst().ifPresentOrElse(tab -> {
                // 将tab显示
                tabContainer.getSelectionModel().select(tab);
            }, new Runnable() {
                @Override
                public void run() {
                    if(StringUtils.isEmpty(menuItem.getView())){
                        log.info("view is empty do nothing ->{}",menuItem);
                        return;
                    }

                    try {
                        AbstractFxmlView tabView = SpringContextutil.getBean(menuItem.getView(),AbstractFxmlView.class);
                        //创建新的tab
                        Tab newTab = new Tab();
                        newTab.setId(String.valueOf(id));
                        newTab.setText(menuItem.getName());
                        newTab.setContent(tabView.getView());
                        ImageView iconImage = new ImageView(menuItem.getIcon());
                        iconImage.setFitHeight(20);
                        iconImage.setPreserveRatio(true);
                        newTab.setGraphic(iconImage);
                        tabContainer.getTabs().add(newTab);
                        tabContainer.getSelectionModel().select(newTab);
                    } catch (Exception e) {
                        log.error("加载页面失败->url->{} error->{}",menuItem.getView(),e);
                    }

                }
            });
        });
    }

    private TreeItem<MenuItem> createTreeItem(MenuItem menuItem){
        TreeItem<MenuItem> item = new TreeItem<>(menuItem);
        item.setExpanded(true);
        if(!StringUtils.isEmpty(menuItem.getIcon())){
            log.info("icon path ->{} id->{} name->{}",menuItem.getIcon(),menuItem.getId(),menuItem.getName());
            ImageView iconImage = new ImageView(menuItem.getIcon());
            iconImage.setFitHeight(16);
            iconImage.setPreserveRatio(true);
            item.setGraphic(iconImage);
        }
        return item;
    }

    private void initLayoutBind(){
        spnMain.prefWidthProperty().bind(pnContainer.widthProperty());
        spnMain.prefHeightProperty().bind(pnContainer.heightProperty().subtract(pnTitle.getPrefHeight()));

        tvLeft.prefWidthProperty().bind(apnLeft.widthProperty());
        tvLeft.prefHeightProperty().bind(apnLeft.heightProperty());

        tabContainer.prefWidthProperty().bind(apnRight.widthProperty());
        tabContainer.prefHeightProperty().bind(apnRight.heightProperty());

    }
}

